package masqiniu

import (
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth"
	"github.com/qiniu/go-sdk/v7/storage"
	"os"
)

type qiniuClient struct {
	key    string
	secret string
	bucket string
	domain string
}

func NewQiniuClient(key, secret, bucket, domain string) *qiniuClient {
	return &qiniuClient{
		key:    key,
		secret: secret,
		bucket: bucket,
		domain: domain,
	}
}

func (s *qiniuClient) Upload(filePath string, filekey string) (filename string, err error) {
	localFile := filePath
	bucket := s.bucket
	key := filekey
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := auth.New(s.key, s.secret)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	resumeUploader := storage.NewResumeUploaderV2(&cfg)
	ret := storage.PutRet{}
	recorder, err := storage.NewFileRecorder(os.TempDir())
	if err != nil {
		fmt.Println(err)
		return
	}
	putExtra := storage.RputV2Extra{
		Recorder: recorder,
	}
	err = resumeUploader.PutFile(context.Background(), &ret, upToken, key, localFile, &putExtra)
	if err != nil {
		fmt.Println(err)
		return
	}
	//fmt.Println(ret.Key, ret.Hash)
	return filekey, nil
}
